package com.qezhhnjy.demo.netty.server;

import com.qezhhnjy.demo.netty.handler.MyChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhaoyangfu
 * @date 2021/6/18-15:17
 */
@Slf4j
public class FirstServer {

    public static void start() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();

        bootstrap.group(boss, work)
            .option(ChannelOption.SO_RCVBUF, 1024)
            .channel(NioServerSocketChannel.class)
            .localAddress(8888)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MyChannelHandler());
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                }
            });

        Channel channel = bootstrap.bind().sync().channel();

        channel.closeFuture().addListener((ChannelFutureListener) future -> {
            log.info("server shutdown...");
            boss.shutdownGracefully();
            work.shutdownGracefully();
        });
    }
}
